export async function getImageDominantColorDarkened(img) {
    return new Promise((resolve, reject) => {
        if (!img.complete || !img.naturalWidth) {
            reject(new Error('Image not loaded'));
            return;
        }

        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            reject(new Error('Canvas not supported'));
            return;
        }

        canvas.width = canvas.height = 32;
        ctx.drawImage(img, 0, 0, 32, 32);

        const data = ctx.getImageData(0, 0, 32, 32).data;
        const colorMap = {};

        for (let i = 0; i < data.length; i += 4) {
            const [r, g, b, a] = data.slice(i, i + 4);
            if (a < 128) continue;

            const key = `${r},${g},${b}`;
            colorMap[key] = (colorMap[key] || 0) + 1;
        }

        let maxKey = '0,0,0';
        let maxCount = 0;
        for (const key in colorMap) {
            if (colorMap[key] > maxCount) {
                maxKey = key;
                maxCount = colorMap[key];
            }
        }

        let [r, g, b] = maxKey.split(',').map(Number);

        // 💡 如果颜色太亮，就压暗（公式简单粗暴：整体拉低亮度）
        const brightness = (r * 299 + g * 587 + b * 114) / 1000;
        if (brightness > 180) {
            r = Math.floor(r * 0.6);
            g = Math.floor(g * 0.6);
            b = Math.floor(b * 0.6);
        }

        resolve(`rgb(${r}, ${g}, ${b})`);
    });
}
